package it.traveldreamWeb.authentification;

import it.traveldream.beans.AccountFactoryInterface;
import it.traveldream.dto.UserDTO;
import it.traveldream.exceptions.InvalidCredentialsException;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

@ManagedBean(name="registerBean")
@ViewScoped
public class RegisterBean {
	
	@EJB
	private AccountFactoryInterface userMgr;
	
	@ManagedProperty(value="#{publicBean}")
	private PublicBean publicSession;

	private UserDTO user;
	private String error;
	
	public RegisterBean() {
		this.user = new UserDTO();
	}

	public String register()   {
		try {
			if (this.publicSession.getReservation() != null){	
				this.user.setInvitationLink(this.publicSession.getInvitationLink());
				this.userMgr.saveCustomer(this.user);
				return "Customer/home?faces-redirect=true";
			} 
			
			this.userMgr.saveCustomer(this.user);
			return "home?faces-redirect=true";
		} catch (InvalidCredentialsException e) {
			this.setError("Invalid request. Not valid credentials or username already taken");
			return null;
		} catch (Exception e){
			this.setError("Internal error. Please try again");
			return null;
		}
	}
	public void setPublicSession(PublicBean publicSession) {
		this.publicSession = publicSession;
	}
	public UserDTO getUser() {
		return this.user;
	}

	public void setUser(UserDTO user) {
		this.user = user;
	}

	public String getError() {
		return this.error;
	}

	public void setError(String error) {
		this.error = error;
	} 
}
